var util = require('../../utils/util.js');
var api = require('../../config/api.js');

Page({
  data: {
    navList: [],
    goodsList: [],
    id: 0,
    parid: 0,//一级分类id
    parname: '',
    currentCategory: {},
    scrollLeft: 0,
    scrollTop: 0,
    scrollHeight: 0,
    page: 1,
    size: 100,


    data: {
      categoryId: 0,
      orderById: 1,
      goodsName: '',
      isOnSale: 1,
    },

    total: '0',
    myAgentList: {
      hasMore: true,
      list: [],
      listSize: 0
    },
    startNum: 1, //页数

    listnum: 10,


  },

  //上拉获取更多列表
  hotActivityLoadMore: function (e) {
    var that = this
    that.listPage()
  },

  //分页查询列表
  listPage: function () {
    var that = this;
    //判断是否还有下一页
    if (that.data.myAgentList.hasMore == true) {
      wx.showLoading({
        title: '加载中',
      })
      var num = that.data.listnum
      var pageNum = that.data.startNum
      var url = 'current=' + pageNum + '&size=' + num
      var data = that.data.data

      util.requestNoToken(api.AllGoodList + url, data, "POST").then(function (res) {
        wx.hideLoading();
        if (res.success) {
          var listSize = res.obj.records.length;
          var newData = that.data.myAgentList.list;
          var lis = res.obj.records;
          lis.forEach(function (item, index, array) {
            array[index] = {
              id: item.id,
              primaryPicUrl: item.primaryPicUrl,
              goodsName: item.goodsName,
              marketPrice: item.marketPrice,
              retailPrice: item.retailPrice,
              categoryName: item.categoryName,
              sellVolume: item.sellVolume,
              goodsBrief: item.goodsBrief
            }
          });
          //concat是在原有基础上进行增加
          newData = newData.concat(lis);
          var newList = {};
          //当长度等于于0表示当前没有数据，停止
          if (listSize == 0) {
            newList.hasMore = false;
            wx.showToast({
              title: "已加载全部列表",
              icon: 'none',
              duration: 2000
            });
            return;
            //当长度小于10表示没有下页数据了
          } else if (listSize < num) {
            wx.showToast({
              title: "已加载全部列表",
              icon: 'none',
              duration: 2000
            });
            newList.hasMore = false;
          } else {
            newList.hasMore = true;
          }
          newList.list = newData;
          console.log("-------newlist:" + JSON.stringify(newList.list))
          newList.listSize = listSize;
          that.setData({
            myAgentList: newList,
            goodsList: newList.list,
          });

          that.setData({
            startNum: pageNum + 1 //页数加1
          })
        } else {
          console.log("获取全部商品列表失败")
        }
      }).catch(function (res) {
        wx.hideLoading();
        console.log("获取数据失败！")
      })
    } else {
      wx.showToast({
        title: "已加载全部商品",
        icon: 'none',
        duration: 2000
      });
    }
  },


  //获取商品列表
  getGoodsList: function () {
    var that = this;
    that.DataLoad()
    var data = that.data.data
    data.categoryId = that.data.id
    var num = that.data.listnum
    var pageNum = that.data.startNum
    var url = 'current=' + pageNum + '&size=' + num;

    util.requestNoToken(api.CatalogGoodList + url, data, "POST").then(function (res) {
      if (res.success) {
        var listSize = res.obj.records.length;
        var newData = that.data.myAgentList.list;
        var lis = res.obj.records;
        lis.forEach(function (item, index, array) {
          array[index] = {
            id: item.id,
            primaryPicUrl: item.primaryPicUrl,
            goodsName: item.goodsName,
            marketPrice: item.marketPrice,
            retailPrice: item.retailPrice,
            categoryName: item.categoryName,
            sellVolume: item.sellVolume,
            goodsBrief: item.goodsBrief,
            isShare: item.isShare
          }
        });
        newData = lis;
        var total1 = res.obj.total;
        var newList = {};
        //当长度小于5表示没有下页数据了
        if (listSize < num) {
          newList.hasMore = false;
        } else {
          newList.hasMore = true;
        }
        newList.list = newData;
        newList.listSize = listSize;
        that.setData({
          myAgentList: newList,
          goodsList: newList.list,
          total: total1
        });
        that.setData({
          startNum: 2
        })
      } else {
        wx.hideLoading();
        console.log("获取全部商品列表失败")
      }
    }).catch(function (res) {
      console.log("获取数据失败！")
    })
  },

  //初始化分页参数
  DataLoad: function (e) {
    var that = this
    var myAgentList = {
      hasMore: true,
      list: [],
      listSize: 0,
    }
    that.setData({
      myAgentList: myAgentList,
      startNum: 1
    })
  },


  // 页面初始化 options为页面跳转所带来的参数
  onLoad: function (options) {

    var that = this;
    if (options.id) {
      that.setData({
        id: parseInt(options.id)
      });
    }
    if (options.parid) {
      that.setData({
        parid: parseInt(options.parid),
        parname: options.parname
      });
    }

    wx.setNavigationBarTitle({
      title: that.data.parname
    })

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          scrollHeight: res.windowHeight
        });
      }
    });

    this.getCategoryInfo();

  },

  //获取当前选择分类
  getCategoryInfo: function () {
    let that = this;
    var parid = that.data.parid
    util.requestNoToken(api.CatalogCurrent + parid, {}, "GET").then(function (res) {
      if (res.success) {
        var list = res.obj.currentSubCategory
        for (var i = 0; i < list.length; i++) {
          if (list[i].id == that.data.id) {
            that.setData({
              currentCategory: list[i]
            });
          }
        }
        that.setData({
          navList: res.obj.currentSubCategory,
        });

        //nav位置
        let currentIndex = 0;
        let navListCount = that.data.navList.length;
        for (let i = 0; i < navListCount; i++) {
          currentIndex += 1;
          if (that.data.navList[i].id == that.data.id) {
            break;
          }
        }
        if (currentIndex > navListCount / 2 && navListCount > 5) {
          that.setData({
            scrollLeft: currentIndex * 60
          });
        }
        that.getGoodsList();

      } else {
        //显示错误信息
      }

    });
  },
  onReady: function () {
    // 页面渲染完成
  },
  onShow: function () {
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },

  onUnload: function () {
    // 页面关闭
  },

  switchCate: function (event) {
    if (this.data.id == event.currentTarget.dataset.id) {
      return false;
    }
    var that = this;
    var clientX = event.detail.x;
    var currentTarget = event.currentTarget;
    if (clientX < 60) {
      that.setData({
        scrollLeft: currentTarget.offsetLeft - 60
      });
    } else if (clientX > 330) {
      that.setData({
        scrollLeft: currentTarget.offsetLeft
      });
    }
    this.setData({
      id: event.currentTarget.dataset.id
    });

    this.getCategoryInfo();
  }
})